/*
*  Copyright 2019-2020
*
*  Licensed under the Apache License, Version 2.0 (the "License");
*  you may not use this file except in compliance with the License.
*  You may obtain a copy of the License at
*
*  http://www.apache.org/licenses/LICENSE-2.0
*
*  Unless required by applicable law or agreed to in writing, software
*  distributed under the License is distributed on an "AS IS" BASIS,
*  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*  See the License for the specific language governing permissions and
*  limitations under the License.
*/
package com.qp.basics.admin.service.impl;

import cn.hutool.core.lang.Snowflake;
import cn.hutool.core.util.IdUtil;
import com.alibaba.fastjson.JSONObject;
import com.qp.basics.admin.repository.DynamicSQLRepository;
import com.qp.basics.admin.repository.EntityHistoryRepository;
import com.qp.basics.admin.service.DynamicSQLService;
import com.qp.basics.admin.service.dto.DynamicSQLQueryCriteria;
import com.qp.basics.common.domain.DynamicSQL;
import com.qp.basics.common.domain.EntityHistory;
import com.qp.basics.common.poi.ExcelX;
import com.qp.basics.common.repository.BaseRepository;
import com.qp.basics.common.service.dto.DynamicSQLDto;
import com.qp.basics.common.service.mapstruct.DynamicSQLMapper;
import com.qp.basics.common.utils.*;

import lombok.RequiredArgsConstructor;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.sql.Timestamp;
import java.util.*;

/**
*
* @description 服务实现
**/
@Service
@RequiredArgsConstructor
public class DynamicSQLServiceImpl implements DynamicSQLService {

    private final DynamicSQLRepository dynamicSQLRepository;
    private final DynamicSQLMapper dynamicSQLMapper;
    private final EntityHistoryRepository entityHistoryRepository;
    private final BaseRepository baseRepository;

    @Override
    public void archives(DynamicSQL resources) {
        EntityHistory entityHistory = new EntityHistory();
        entityHistory.setEntityId(resources.getId());
        entityHistory.setEntityName("DynamicSQL");
        entityHistory.setEntityTitle(resources.getName());
        entityHistory.setContent(resources.getQueryStr());
        entityHistory.setComment(resources.getRemark());
        entityHistory.setCreateTime(new Timestamp(new Date().getTime()));
        entityHistory.setCreateBy(SecurityUtils.getCurrentUsername());
        entityHistoryRepository.save(entityHistory);
        if(resources.getSaveTimes() != null){
            resources.setSaveTimes(resources.getSaveTimes()+1l);
        }else {
            resources.setSaveTimes(1l);
        }
        dynamicSQLRepository.save(resources);
    }

    @Override
    public Map<String,Object> queryAll(DynamicSQLQueryCriteria criteria, Pageable pageable){
        Page<DynamicSQL> page = dynamicSQLRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root,criteria,criteriaBuilder),pageable);
        return PageUtil.toPage(page.map(dynamicSQLMapper::toDto));
    }

    @Override
    public List<DynamicSQLDto> queryAll(DynamicSQLQueryCriteria criteria){
        return dynamicSQLMapper.toDto(dynamicSQLRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root,criteria,criteriaBuilder)));
    }

    @Override
    @Transactional
    public DynamicSQLDto findById(Long id) {
        DynamicSQL dynamicSQL = dynamicSQLRepository.findById(id).orElseGet(DynamicSQL::new);
        ValidationUtil.isNull(dynamicSQL.getId(),"DynamicSQL","id",id);
        return dynamicSQLMapper.toDto(dynamicSQL);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public DynamicSQLDto create(DynamicSQL resources) {
        Snowflake snowflake = IdUtil.createSnowflake(1, 1);
        resources.setId(snowflake.nextId());
        String sql = "SELECT count(1) count FROM dynamicsql WHERE `name` = '" + resources.getName() + "'";
        List<Map> resList = baseRepository.findMapByNativeSql(sql);
        if (Integer.parseInt(resList.get(0).get("count").toString()) >0){
            throw new RuntimeException("名称重复");
        }
        return dynamicSQLMapper.toDto(dynamicSQLRepository.save(resources));
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void update(DynamicSQL resources) {
        DynamicSQL dynamicSQL = dynamicSQLRepository.findById(resources.getId()).orElseGet(DynamicSQL::new);
        ValidationUtil.isNull( dynamicSQL.getId(),"DynamicSQL","id",resources.getId());
        resources.setId(dynamicSQL.getId());
        DynamicSQL ds = (DynamicSQL)baseRepository.queryUniqueResult("from DynamicSQL where name='"+resources.getName()+"'",null);
        if (ds != null && !ds.getId().equals(resources.getId())){
            throw new RuntimeException("名称重复");
        }
        dynamicSQLRepository.save(resources);
    }

    @Override
    public void deleteAll(Long[] ids) {
        for (Long id : ids) {
            dynamicSQLRepository.deleteById(id);
        }
    }

    @Override
    public void download(List<DynamicSQLDto> all, HttpServletResponse response) throws IOException {
        List<Map<String, Object>> list = new ArrayList<>();
        for (DynamicSQLDto dynamicSQL : all) {
            Map<String,Object> map = new LinkedHashMap<>();
            map.put("名称", dynamicSQL.getName());
            map.put("查询语句", dynamicSQL.getQueryStr());
            map.put("sql还是hql", dynamicSQL.getQueryStrType());
            map.put("结果类", dynamicSQL.getResultType());
            map.put("使用说明", dynamicSQL.getRemark());
            map.put("转换方法", dynamicSQL.getConvertor());
            list.add(map);
        }
        FileUtil.downloadExcel(list, response);
    }
    @Override
    public JSONObject importExcel(MultipartFile file) {
        JSONObject res=new JSONObject();

        try (InputStream is = file.getInputStream()) {
            ExcelX ex = new ExcelX(is);
            List<Map> l = ex.excelToMapList(0);
            int count=0;
            for (int i = 0; i < l.size(); i++) {
                Map m = l.get(i);
                Object t = m.get("id");
                if (t == null || "".equals(t)) {
                    continue;
                }
                //String title = m.get("题目").toString();
                DynamicSQL q = new DynamicSQL();
                //q.setTitle(title);
                q = dynamicSQLRepository.save(q);
                count++;
            }
            res.put("msg","导入成功：共导入"+count+"条");
        } catch (IOException e) {
            e.printStackTrace();
            res.put("msg","导入失败："+e.getMessage());
        }
        return res;
    }
}
